import {
  forwardRef,
  ForwardRefRenderFunction,
  useImperativeHandle,
  useRef,
} from "react";

interface UncontrolledProps {
  defaultValue?: string;
}

export interface RefProps {
  value: string | undefined;
}

const Uncontrolled: ForwardRefRenderFunction<RefProps, UncontrolledProps> = (
  props,
  ref
) => {
  const { defaultValue } = props;

  const inpRef = useRef<HTMLInputElement>(null);

  // 设置当前组件暴露的ref的值
  useImperativeHandle(
    ref,
    () => {
      return {
        get value() {
          return inpRef.current?.value;
        },
      };
    },
    [inpRef]
  );

  return (
    <>
      <input type="text" ref={inpRef} defaultValue={defaultValue} />
    </>
  );
};

export default forwardRef(Uncontrolled);
